<template>
    <el-dialog title="图片裁剪" width="70%" :visible.sync="cropDiaShow" :before-close="closeCrop" class="icon-dialog" append-to-body>
        <div style="height:500px">
            <VueCropper
                ref="cropper"
                :img="example.img"
                :output-size="example.size"
                :output-type="example.outputType"
                :info="example.info"
                :can-move='example.canMove'
                :fixed-box="example.fixedBox"
                :center-box="example.centerBox"
                :can-scale="example.canScale"
                :auto-crop="example.autoCrop"
                :auto-crop-width="example.autoCropWidth"
                :auto-crop-height="example.autoCropHeight"
                :fixed="example.fixed"
                :fixed-number="example.fixedNumber"
                >
            </VueCropper>
            </div>
            <div style="text-align:center; margin-top:15px;">
                <div class="scope-btn">
                    <el-button size="mini" type="danger" plain icon="el-icon-zoom-in" @click="changeScale(1)">放大</el-button>
                    <el-button size="mini" type="danger" plain icon="el-icon-zoom-out" @click="changeScale(-1)">缩小</el-button>
                    <el-button size="mini" type="danger" plain @click="rotateLeft">↺ 左旋转</el-button>
                    <el-button size="mini" type="danger" plain @click="rotateRight">↻ 右旋转</el-button>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitCrop" >
                    <span>确 定</span>
                </el-button>
                <el-button size="small" @click="closeCrop">取 消</el-button>
            </div>
    </el-dialog>
</template>

<script>
import {VueCropper} from 'vue-cropper'
export default {
    components: { VueCropper },
    props: {
        cropDiaShow: {
            type: Boolean,
            default: false
        },
        imgbase64:{
            type:String,
        },
        cropFileName:{
            type:String,
        },
        cropsize:{
            type:String,
        },
        rename:{
            type:String,
        },
    },
    watch:{
        imgbase64(val){
            let size = this.cropsize.replace("，",",").split(",")
            this.example.autoCropWidth = size[0]
            this.example.autoCropHeight = size[1]
            this.example.img = val
        },
    },
    data() {
        return {
            loading: false,
            progressPercent:0,
            progress:false,
            example: {
                img: '', 					// 裁剪图片的地址	可选值：url 地址 || base64 || blob
                info: true,                 // 裁剪框的大小信息	可选值：true || false
                size: 1,                    // 裁剪生成图片的质量    可选值：0.1 - 1
                outputType:'png',           // 裁剪生成图片的格式    可选值：jpeg || png || webp
                canScale: true,             // 图片是否允许滚轮缩放     可选值：true || false
                autoCrop: true,             // 是否默认生成截图框
                canMove:true,	              // 上传图片是否可以移动 可选值：true | false
                fixedBox:false,             // 固定截图框大小 不允许改变  可选值：true | false
                centerBox:false,            // 截图框是否被限制在图片里面
                autoCropWidth: '',
                autoCropHeight: '',
                fixed: false,                // 开启宽度和高度比例
                fixedNumber: [1, 1]
            },
        }
    },
    methods: {
        submitCrop(){
            this.loading = true
            let that = this;
            this.$refs.cropper.getCropBlob(async (data) => {
                const time = new Date().getTime()
                let file = new window.File([data], this.cropFileName, {
                    type: data.type,
                });
                this.upload(file)
            })
        },
        upload(file){
            let formdata = new FormData()
            let ali = new FormData()  //此处非常坑 阿里上传file属性必须要放到最后  所以只能赋值对象
            formdata.append('file', file)
            formdata.append('rename', this.rename)
            try {
                this.$axios.post('/admin/Upload/upload', formdata).then(res => {
                    if(res.data.status == 200){
                        if(res.data.filestatus){
                            this.setFilePath(file,res.data.data)
                        }else{
                            if(res.data.data.type == 'qiniuyun'){
                                formdata.append('token',res.data.data.token)
                                formdata.append('key',res.data.data.key)
                                axios.post(res.data.data.serverurl, formdata,config).then(ret => {
                                    if(ret.data.key){
                                        this.$axios.post('/admin/Upload/createFile',{filepath:res.data.data.domain+'/'+ret.data.key}).then(result => {
                                            this.setFilePath(file,res.data.data.domain+'/'+ret.data.key)
                                        })
                                    }
                                })
                            }else if(res.data.data.type == 'tencent'){
                                let vm = this
                                $.getScript("/assets/js/cos-js-sdk-v5.min.js",function(script){
                                    var cos = new COS({
                                        SecretId: res.data.data.SecretId,
                                        SecretKey: res.data.data.SecretKey
                                    });
                                    cos.putObject({
                                        Bucket: res.data.data.Bucket, // 桶名-APPID  必须
                                        Region: res.data.data.Region, //区域 必须
                                        Schema: res.data.data.Schema, //区域 必须
                                        Key: res.data.data.key, //文件名必须 
                                        Body: file, // 上传文件对象
                                        onProgress: function (progressData) {
                                        }
                                    }, function (err, data) {
                                        if(data.Location){
                                            const url = res.data.data.Schema+'://'+data.Location
                                            this.$axios.post('/admin/Upload/createFile',{filepath:url}).then(result => {
                                                vm.setFilePath(file,url)
                                            })
                                        }
                                    })
                                })
                            }else if(res.data.data.type == 'ali'){
                                ali.append('Signature',res.data.data.sign)
                                ali.append('callback',res.data.data.callback)
                                ali.append('OSSAccessKeyId',res.data.data.OSSAccessKeyId)
                                ali.append('policy',res.data.data.policy)
                                ali.append('key',res.data.data.key)
                                ali.append('file', file)
                                axios.post(res.data.data.serverurl, ali,config).then(ret => {
                                    if(ret.data.code == 1){
                                        this.$axios.post('/admin/Upload/createFile',{filepath:ret.data.data}).then(result => {
                                            this.setFilePath(file,ret.data.data)
                                        })
                                    }
                                })
                            }else{
                                this.setFilePath(file,res.data.data)
                            }
                        }
                    }else{
                        this.$message.error('上传失败')
                    }
                })
            }catch (error) {
                this.$message.error('上传失败')
            }finally {
                this.$refs.upload && this.$refs.upload.clearFiles()
            }
        },
        setFilePath(item,filepath){
            this.$emit('update:siglepic', filepath)
            this.$emit('update:cropDiaShow', false)
        },
        //图片缩放
        changeScale (num) {
            num = num || 1
            this.$refs.cropper.changeScale(num)
        },
        //向左旋转
        rotateLeft () {
            this.$refs.cropper.rotateLeft()
        },
        //向右旋转
        rotateRight () {
            this.$refs.cropper.rotateRight()
        },
        closeCrop(){
            this.$emit('update:cropDiaShow', false)
            this.example.img = ""
        }
    },    
};
</script>
